﻿using Microsoft.SharePoint.Administration;

namespace SPSDeploy.Extensions.Extensions
{
    /// <summary>
    /// Service application proxy extensions
    /// </summary>
    internal static class ServiceApplicationProxyExtension
    {

        /// <summary>
        /// Return service application proxy instance
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static SPServiceApplicationProxy GetServiceApplicationProxy(string name, string type)
        {
            SPFarm farm = SPFarm.Local;
            foreach (SPServiceProxy serviceProxy in farm.ServiceProxies)
                foreach (SPServiceApplicationProxy applicationProxy in serviceProxy.ApplicationProxies)
                    if (applicationProxy.DisplayName == name && applicationProxy.TypeName == type)
                        return applicationProxy;
            return null;
        }

        /// <summary>
        /// Check if service application proxy exists
        /// </summary>
        /// <param name="proxies"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static bool ServiceApplicationProxyExists(SPServiceProxyCollection proxies, string name, string type)
        {
            foreach (SPServiceProxy serviceProxy in proxies)
                foreach (SPServiceApplicationProxy applicationProxy in serviceProxy.ApplicationProxies)
                    if (applicationProxy.DisplayName == name && applicationProxy.TypeName == type)
                        return true;
            return false;
        }

        /// <summary>
        /// Check if the proxy should be included
        /// </summary>
        /// <param name="farm"></param>
        /// <param name="applicationProxy"></param>
        /// <returns></returns>
        internal static bool IncludeProxy(SPFarm farm, SPServiceApplicationProxy applicationProxy)
        {
            foreach (SPService service in farm.Services)
                foreach (SPServiceApplication application in service.Applications)
                    if (application.IsConnected(applicationProxy))
                        return false;
            return true;
        }

    }
}